package com.shanghaionstar.home.presenter;

import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.onstar.cn.auth.AuthPinTokenEntity;
import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.auth.userProfile.AppVersion;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.function.FunctionInfo;
import com.onstar.cn.mag.enumtype.CategoryType;
import com.onstar.cn.mag.publicService.response.H5DispatcherResEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.weight.discover.ItemViewData;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.KuaiDaDiWebHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.discover.violation.VehicleViolationActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.function.ShortCutManager;
import com.shanghaionstar.home.iview.IHomeView;
import com.shanghaionstar.home.model.HomeModel;
import com.shanghaionstar.home.service.HomeService;
import com.shanghaionstar.login.presenter.RetryWithDelay;
import com.shanghaionstar.login.service.AuthorService;
import com.shanghaionstar.login.service.LoginSerice;
import com.shanghaionstar.login.service.LoginTransformHelper;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BannerUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/6/24.
 */
public class HomePresenter extends BasePresenter<HomeModel> {

    private ShortCutManager shortCutsDBService;
    private IHomeView homeView;
    private BaseActivity mContext;
    private HomeService service;
    private LoginSerice loginService;

    private int mCacheState = LoginTransformHelper.CACHE_STATE_NONE;

    public HomePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<HomeModel> view) {
        super.setView(view);
        homeView = (IHomeView) view;
        mContext = (BaseActivity) view.onActivity();
        shortCutsDBService = new ShortCutManager(mContext);
        service = new HomeService(mContext);
        loginService = new LoginSerice(mContext);
    }

    /**
     * 根据是否存在设备列表显示相关fragment
     */
    public void getServiceStatus() {
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(mContext);
        subscription = service.getServiceStatus(requestEntity, Constants.SMART_DRIVER).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<ServiceItem>>() {
                    @Override
                    public void call(List<ServiceItem> items) {
                        ServiceItem item = items.get(0);
                        if (item != null && item.availability.equalsIgnoreCase("1")) {// 0: 不可用(隐藏); 1: 可用(展现)

                            if (item.optStatus != null) {//  0: 关闭; 1: 开启; 2: 开通中; 3: 失败(客户端显示为关闭)
                                if (item.optStatus.equalsIgnoreCase("0") || item.optStatus.equalsIgnoreCase("3")) {
                                    PreferencesUtls.getInstance(mContext).putBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, false);
                                } else if (item.optStatus.equalsIgnoreCase("1")) {
                                    PreferencesUtls.getInstance(mContext).putBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, true);
                                } else {
                                    PreferencesUtls.getInstance(mContext).putBoolean(FinalConstants.SharedPreferencesConfig.AGREED_BEHAVIOR, false);
                                }
                            }
                            String loginRole = ApplicationUtil.getInstance().getLoginRole();
                            boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
                            if (homeView != null && mContext != null && isOwner && !ApplicationUtil.getInstance().isPhev())
                                homeView.showSmartDriver(true);
                        } else {
                            if (homeView != null && mContext != null)
                                homeView.showSmartDriver(false);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (homeView != null && mContext != null)
                            homeView.showSmartDriver(false);
                    }
                });
    }

    public void showMro() {
        if (!ApplicationUtil.getInstance().isLogin()) {
            homeView.showMro(false);
        } else {
            boolean isShowMro = PreferencesUtls.getInstance(mContext)
                    .getBoolean(FinalConstants.SharedPreferencesConfig.IS_USE_MRO(mContext), true);
            String loginRole = ApplicationUtil.getInstance().getLoginRole();
            boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
            if (DeviceUtil.isChineseLanguage() && isShowMro && isOwner) {
                homeView.showMro(true);
            } else {
                homeView.showMro(false);
            }
        }
    }

    public void getH5(final PreferentialResEntity entity) {
        view.setLoading(true);
        BannerUtil bannerUtil = new BannerUtil(view.onActivity());
        subscription = bannerUtil.h5Dispatcher(entity).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<H5DispatcherResEntity>() {
                    @Override
                    public void call(H5DispatcherResEntity mResult) {
                        view.setLoading(false);
                        String url = mResult.getUrl();
                        String title = entity.getTitle();
                        if (!TextUtils.isEmpty(url))
                            launchWeb(url,title);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        view.setLoading(false);
                    }
                });
    }

    public void launchWeb(String h5Url,String title) {
        if (TextUtils.isEmpty(h5Url)) {
            LogManager.getInstance().d("launchDetail...h5Url is blank");
            return;
        }
        WebDataEntity entity = new WebDataEntity();
        entity.setLinkUrl(h5Url);
        entity.setTopTitle(title);
        if (h5Url.contains("kuaidadi")) {
            entity.setWhat(IWebType.TYPE_LOCATION);
            entity.setClzName(KuaiDaDiWebHandler.class.getName());
        } else
            entity.setWhat(IWebType.TYPE_NORMAL);
        CommonWebViewActivity.launchCommonWeb(view.onActivity(), entity);
    }

    public void getShortCuts() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<FunctionInfo> list = shortCutsDBService.getShortCuts();
                if (list != null && list.size() > 0) {
                    final List<ItemViewData> itemViews = new ArrayList<ItemViewData>();
                    for (FunctionInfo shortCutsEntity : list) {
                        if (shortCutsEntity.getActivity().equals(VehicleViolationActivity.class.getName()))
                            continue;
                        ItemViewData itemViewData = new ItemViewData();
                        itemViewData.setText(shortCutsEntity.getTitle());
                        itemViewData.setIcon(shortCutsEntity.getIconResId());
                        itemViewData.setClassName(shortCutsEntity.getActivity());
                        Bundle bundle = new Bundle();
                        bundle.putString(FinalConstants.JUMP_FLAG, shortCutsEntity.getFragment());
                        itemViewData.setBundle(bundle);
                        itemViewData.setFunctionValue(shortCutsEntity.getFunctionNameFindId());
                        itemViews.add(itemViewData);
                    }
                    mContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            homeView.onShowShortCuts(itemViews);
                        }
                    });
                }
            }
        }).start();
    }

    public void commandData() {
        BannerUtil util = new BannerUtil(mContext);
        subscription = util.commandDataList(CategoryType.HOME_BANNER.value()).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<List<ResponBannerEntity>>() {
                    @Override
                    public void call(List<ResponBannerEntity> myDiscountResps) {
                        if (myDiscountResps == null || myDiscountResps.isEmpty()) {
                            homeView.onShowBanner(null);
                        } else {
                            homeView.onShowBanner(myDiscountResps);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        homeView.onShowBanner(null);
                    }
                });
    }

//    private void reportPartner(String url) {
//        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);;
//        requestEntity.setUrl(url);
//        requestEntity.setMethod(HttpMethod.GET.value());
//        new Sender().send(requestEntity);
//    }


    public void bannerClick(ResponBannerEntity entity) {
        BannerUtil util = new BannerUtil(mContext);
        util.bannerClick(entity, mContext, FunctionNameFindId.Home_Banner, mvpScheduler, homeView);
    }


    //*****************客户端登录缓存**************************//
//    public void cacheLogin() {
//        String idToken = PreferencesUtls.getInstance(mContext).getString(Constants.ID_TOKEN);
//        if (CommonUtil.isNull(idToken)) {
//            return;
//        }
//        String userProfileJson = PreferencesUtls.getInstance(mContext).getString(
//                Constants.AUTH_USER_PROFILE);
//        LogManager.getInstance().d("userProfileJson--->" + userProfileJson);
//        if (CommonUtil.isNull(userProfileJson)) {
//            autoLogin();
//        } else {
//            if (BusinessUtil.checkTokenExpired(mContext)) {
//                refreshAccessToken(userProfileJson);
//            } else {
//                loadCacheProfileCommands(userProfileJson);
//            }
//        }
//    }


//    private void loadCacheCommands(Subscriber subscriber) {
//        String accessToken = PreferencesUtls.getInstance(mContext).getString(Constants.ACCESS_TOKEN);
//        String[] tokenSplit = accessToken.split("@");
//        String featureJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_FEATURE);
//        LogManager.getInstance().d("featureJson---->" + featureJson);
//        if (tokenSplit.length == 2) {
//            accessToken = tokenSplit[1];
//        }
//        ApplicationUtil.updateToken(mContext, "", accessToken);
//        ApplicationUtil.updateUserProfile(mContext, subscriber);
//        if (!CommonUtil.isNull(featureJson) && !JoinMeConstants.VISITOR.equalsIgnoreCase(subscriber.getRole())) {
//            ServiceFeatureCommandEntity entity = JsonParseUtil.JsonToBean(ServiceFeatureCommandEntity.class,
//                    featureJson);
//            ApplicationUtil.updateVehicleUnitFeatures(mContext, entity);
//        }
//    }


//    private Observable<Subscriber> checkLocalProfile() {
//        String subscriberJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_PROFILE, "");
//        if (!TextUtils.isEmpty(subscriberJson)) {
//            try {
//                Subscriber subscriber = new Gson().fromJson(subscriberJson, Subscriber.class);
//                new LoginSerice(mContext).handleSubscriber(subscriber);
//                return Observable.just(subscriber);
//            } catch (OnStarException e) {
//                e.printStackTrace();
//            }
//        }
//        return new LoginSerice(mContext).loadUserProfile4Cache();
//    }

    public void autoLoginWithCache() {
       String idToken =  PreferencesUtls.getInstance(mContext).getString(Constants.ID_TOKEN);
        if(!CommonUtil.isNull(idToken) && !BusinessUtil.checkIDTokenExpired(mContext)) {
            ApplicationUtil.getInstance().setAutoLoging(true);
            if (homeView != null) {
                homeView.isAutoLogin();
            }
            AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
            entity.setAutoLogin(true);
            AuthorService authorService = new AuthorService(mContext);
            BusinessUtil.sendReportByClickType(mContext, FunctionNameFindId.Login_GetToken.getStringValue());
            doCacheLogin(authorService, entity);
        }
    }

    private void doCacheLogin(AuthorService authorService, AuthTokenRequestEntity entity) {
        authorService.pinReauthForNoPin(entity)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .doOnNext(new Action1<AuthPinTokenEntity>() {
                    @Override
                    public void call(AuthPinTokenEntity authPinTokenEntity) {
                        checkLocalCache();
                    }
                }).subscribe(new Action1<AuthPinTokenEntity>() {
            @Override
            public void call(AuthPinTokenEntity authPinTokenEntity) {
                loadUserProfileBehind();
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                cacheLoginFailed(throwable);
            }
        });
    }

    private void cacheLoginFailed(Throwable throwable) {
        if (homeView != null) {
            homeView.notLogin();
        }
        ApplicationUtil.getInstance().setAutoLoging( false);
        BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.loginregister_Login.getStringValue(), ReportReqParam.getLoginReqParm(false, throwable.getMessage()));
        OnStarException onStarException = (OnStarException) throwable;
        //后期需要加上这段代码，注释仅仅是为了调试
        AuthorUtil.getInstance().loginOut(mContext);
        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
                (mContext, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
        if (homeView != null) {
            homeView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
        }
    }

    private void checkLocalCache() {
        String subscriberJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_PROFILE, "");
        if (!TextUtils.isEmpty(subscriberJson)) {
            setupCacheSubscriber(subscriberJson);
            long cacheTime = PreferencesUtls.getInstance(mContext).getLong(Constants.AUTH_USER_PROFILE_TIME, -1);
            if (LoginTransformHelper.detectCacheExpiration(cacheTime)) {
                homeView.onBehindGetData(mCacheState = LoginTransformHelper.CACHE_STATE_EXPIRED);
            } else {
                homeView.onBehindGetData(mCacheState = LoginTransformHelper.CACHE_STATE_NORMAL);
            }
            loginService.onSuccess();
        } else {
            homeView.onBehindGetData(mCacheState = LoginTransformHelper.CACHE_STATE_NOCACHE);
        }
        OnstarApplication.getApplication().setmLoginState(mCacheState);
    }

    private void loadUserProfileBehind() {
        loginService.loadUserProfile4Cache()
                .retryWhen(new RetryWithDelay(3,3000))
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<Subscriber>() {
                    @Override
                    public void call(Subscriber subscriber) {
                        OnstarApplication.getApplication().setmLoginState(LoginTransformHelper.CACHE_STATE_UPDATE);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        OnstarApplication.getApplication().setmLoginState(LoginTransformHelper.CACHE_STATE_ERROR);
                        AlertDialogUtil.showAlertDialog(mContext, mContext.getString(R.string.dialog_warning),
                                mContext.getString(R.string.login_state_failed));
                        //里面抛出的Error信息
                        checkForceUpgrade(throwable);
                        }
                });
    }

    private void checkForceUpgrade(Throwable throwable) {
        if (homeView != null) {
            homeView.notLogin();
        }
        ApplicationUtil.getInstance().setAutoLoging( false);
        ReportReqParam reportReqParam = new ReportReqParam.ReportReqParamBuilder().channelId("0")
                .deviceType("0")
                .functionNameFindId(FunctionNameFindId.loginregister_Login.getStringValue())
                .objectID("")
                .objectType("9")
                .operationType("")
                .result("1")
                .type("3")
                .error(throwable.getMessage()).createReportReqParam();
        BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.loginregister_Login.getStringValue(), reportReqParam);
        OnStarException onStarException = (OnStarException) throwable;
        AuthorUtil.getInstance().loginOut(mContext);
        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
                (mContext, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
        /**
         * 強制升級
         */
        if (!CommonUtil.isNull(onStarException.getErrorCode())
                && onStarException.getErrorCode().equalsIgnoreCase(ErrorEnum.E9004.getStringValue())) {
            if (homeView != null) {
                homeView.showUpgrade(onStarException);
            }
        } else {
            if (homeView != null) {
                homeView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
            }
        }
    }

    private void setupCacheSubscriber(String subscriberJson) {
        try {
            Subscriber subscriber = new Gson().fromJson(subscriberJson, Subscriber.class);
            loginService.loadCacheCommands(subscriber);
            handleSubscriberOnMain(subscriber);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public void autoLogin4Cache() {
//        loginService = new LoginSerice(mContext);
//        String idToken = PreferencesUtls.getInstance(mContext).getString(Constants.ID_TOKEN);
//        if (CommonUtil.isNull(idToken) || BusinessUtil.checkIDTokenExpired(mContext)) {
//            return;
//        }
//        ApplicationUtil.updateAutoLogings(mContext, true);
//        if (homeView != null) {
//            homeView.isAutoLogin();
//        }
//        AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
//        AuthorService authorService = new AuthorService(mContext);
//        authorService.pinReauthForNoPin(entity)
//                .subscribeOn(mvpScheduler.backgroundThread())
//                .observeOn(mvpScheduler.mainThread())
//                .doOnNext(new Action1<AuthPinTokenEntity>() {
//                    @Override
//                    public void call(AuthPinTokenEntity authPinTokenEntity) {
//                        String subscriberJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_PROFILE, "");
//                        if (!TextUtils.isEmpty(subscriberJson)) {
//                            try {
//                                Subscriber subscriber = new Gson().fromJson(subscriberJson, Subscriber.class);
//                                loginService.loadCacheCommands(subscriber);
//                                loginService.onSuccess();
//                                handleSubscriberOnMain(subscriber);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        } else {
//                            loadProfileBehind();
//                        }
//                    }
//                })
//                .flatMap(new Func1<AuthPinTokenEntity, Observable<AuthPinTokenEntity>>() {
//                    @Override
//                    public Observable<AuthPinTokenEntity> call(AuthPinTokenEntity authPinTokenEntity) {
//                        String subscriberJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_PROFILE, "");
//                        if (!TextUtils.isEmpty(subscriberJson)) {
//                            try {
//                                Subscriber subscriber = new Gson().fromJson(subscriberJson, Subscriber.class);
//                                loginService.loadCacheCommands(subscriber);
//                                loginService.onSuccess();
//                                handleSubscriberOnMain(subscriber);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        } else {
//                            loadProfileBehind();
//                        }
//                        return Observable.just(authPinTokenEntity);
//                    }
//                })
//                .subscribeOn(mvpScheduler.backgroundThread())
//                .observeOn(mvpScheduler.mainThread())
//                .subscribe(new Action1<AuthPinTokenEntity>() {
//                    @Override
//                    public void call(AuthPinTokenEntity authPinTokenEntity) {
//                        loadProfileBehind();
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        //里面抛出的Error信息
//                        cacheLoginFailed(throwable);
//                    }
//                });
//    }

//    private void loadProfileBehind() {
//        loginService.loadUserProfile4Cache()
//                .subscribeOn(mvpScheduler.backgroundThread())
//                .observeOn(mvpScheduler.mainThread())
//                .subscribe(new Action1<Subscriber>() {
//                    @Override
//                    public void call(Subscriber subscriber) {
//                        handleSubscriberOnMain(subscriber);
//                    }
//                }, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        //里面抛出的Error信息
//                        if (homeView != null) {
//                            homeView.notLogin();
//                        }
//                        ApplicationUtil.updateAutoLogings(OnstarApplication.getApplication(), false);
//                        BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.loginregister_Login.getStringValue(), ReportReqParam.getLoginReqParm(false, throwable.getMessage()));
//                        OnStarException onStarException = (OnStarException) throwable;
//                        //后期需要加上这段代码，注释仅仅是为了调试
//                        AuthorUtil.getInstance().loginOut(mContext);
//                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
//                                (mContext, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
//                        /**
//                         * 強制升級
//                         */
//                        if (!CommonUtil.isNull(onStarException.getErrorCode())
//                                && onStarException.getErrorCode().equalsIgnoreCase(ErrorEnum.E9004.getStringValue())) {
//                            if (homeView != null) {
//                                homeView.showUpgrade(onStarException);
//                            }
//                        } else {
//                            if (homeView != null) {
//                                homeView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
//                            }
//                        }
//                    }
//                });
//    }

    private void handleSubscriberOnMain(Subscriber subscriber) {
        if (!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
                && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
            /**
             * 访客直接成功登陆，不需要执行vehicle feature 方法
             */
        } else {
            /**
             * tdb 没有处理 UPGRADE_NEW_VERSION_OPTIONAL？
             */
            if (subscriber != null && subscriber.getApp() != null) {
                AppVersion app = subscriber.getApp();
                if (!CommonUtil.isNull(app.getVersionCode()) && CommonUtil.isInt(app.getVersionCode())) {
                    if (Integer.parseInt(app.getVersionCode()) > new DeviceUtil(mContext).getAppVersionCode()) {
                    }
                }
            }
        }
    }

//    public void refreshAccessToken(final String userProfileJson) {
//        new AuthorUtil().reauthForNoPin(mContext, new Action1() {
//            @Override
//            public void call(Object o) {
//                loadCacheProfileCommands(userProfileJson);
//            }
//        }, new Action1<Throwable>() {
//            @Override
//            public void call(Throwable throwable) {
//            }
//        });
//    }

//    private void loadCacheProfileCommands(String userProfileJson) {
//        String accessToken = PreferencesUtls.getInstance(mContext).getString(Constants.ACCESS_TOKEN);
//        String[] tokenSplit = accessToken.split("@");
//        Subscriber subscriber = JsonParseUtil.JsonToBean(Subscriber.class, userProfileJson);
//        String featureJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_FEATURE);
//        if (tokenSplit.length == 2) {
//            accessToken = tokenSplit[1];
//        }
//        ApplicationUtil.updateToken(mContext, "", accessToken);
//        ApplicationUtil.updateUserProfile(mContext, subscriber);
//        if (!CommonUtil.isNull(featureJson) && !JoinMeConstants.VISITOR.equalsIgnoreCase(subscriber.getRole())) {
//            ServiceFeatureCommandEntity entity = JsonParseUtil.JsonToBean(ServiceFeatureCommandEntity.class,
//                    featureJson);
//            ApplicationUtil.updateVehicleUnitFeatures(mContext, entity);
//        }
//        mContext.startService(new Intent(mContext, RefreshCommandsService.class));
//    }

//    public void autoLogin() {
//        String idToken = PreferencesUtls.getInstance(mContext).getString(Constants.ID_TOKEN);
//        if (CommonUtil.isNull(idToken) || BusinessUtil.checkIDTokenExpired(mContext)) {
//            return;
//        }
//        ApplicationUtil.updateAutoLogings(mContext, true);
//        String subscriberJson = PreferencesUtls.getInstance(mContext).getString(Constants.AUTH_USER_PROFILE, "");
//
//        if (!TextUtils.isEmpty(subscriberJson)) {
//            try {
//                Subscriber subscriber = new Gson().fromJson(subscriberJson, Subscriber.class);
//                new LoginSerice(mContext).handleSubscriber(subscriber);
//                handleSubscriberOnMain(subscriber);
//            } catch (OnStarException e) {
//                e.printStackTrace();
//            }
//        } else {
//            if (homeView != null) {
//                homeView.isAutoLogin();
//            }
//            AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
//            AuthorService authorService = new AuthorService(mContext);
//            authorService.pinReauthForNoPin(entity)
//                    .flatMap(new Func1<AuthPinTokenEntity, Observable<Subscriber>>() {
//                        @Override
//                        public Observable<Subscriber> call(AuthPinTokenEntity authPinTokenEntity) {
//
//                            return new LoginSerice(mContext).loadUserProfile();
//                        }
//                    })
//                    .subscribeOn(mvpScheduler.backgroundThread())
//                    .observeOn(mvpScheduler.mainThread())
//                    .subscribe(new Action1<Subscriber>() {
//                        @Override
//                        public void call(Subscriber subscriber) {
//                            handleSubscriberOnMain(subscriber);
////                        onSuccess();
//                        }
//                    }, new Action1<Throwable>() {
//                        @Override
//                        public void call(Throwable throwable) {
//                            //里面抛出的Error信息
//                            if (homeView != null) {
//                                homeView.notLogin();
//                            }
//                            ApplicationUtil.updateAutoLogings(OnstarApplication.getApplication(), false);
//                            ReportReqParam reportReqParam = new ReportReqParam.ReportReqParamBuilder().channelId("0")
//                                    .deviceType("0")
//                                    .functionNameFindId(FunctionNameFindId.loginregister_Login.getStringValue())
//                                    .objectID("")
//                                    .objectType("9")
//                                    .operationType("")
//                                    .result("1")
//                                    .type("3")
//                                    .error(throwable.getMessage()).createReportReqParam();
//                            BusinessUtil.sendReportByRequestParams(mContext, FunctionNameFindId.loginregister_Login.getStringValue(), reportReqParam);
//                            OnStarException onStarException = (OnStarException) throwable;
//                            AuthorUtil.getInstance().loginOut(mContext);
//                            ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
//                                    (mContext, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
//                            /**
//                             * 強制升級
//                             */
//                            if (!CommonUtil.isNull(onStarException.getErrorCode())
//                                    && onStarException.getErrorCode().equalsIgnoreCase(ErrorEnum.E9004.getStringValue())) {
//                                if (homeView != null) {
//                                    homeView.showUpgrade(onStarException);
//                                }
//                            } else {
//                                if (homeView != null) {
//                                    homeView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));
//                                }
//                            }
//                        }
//                    });
//        }
//    }
}
